package cn.mengfly.testnrz.netty.protobuf;

import cn.mengfly.testnrz.util.BootStrapUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

public class ProtoBufSendClient {

    Bootstrap b = new Bootstrap();

    public void runClient() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            BootStrapUtil.initClient(b, workerGroup);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                    ch.pipeline().addLast(new ProtobufEncoder());
                }
            });
            ChannelFuture connect = b.connect();
            connect.sync();
            Channel channel = connect.channel();
            MsgProtos.Msg.Builder builder = MsgProtos.Msg.newBuilder();
            for (int i = 0; i < 100; i++) {
                builder.setId(i);
                builder.setContent("这是一条测试数据");
                channel.writeAndFlush(builder.build());
                System.out.println("发送成功" + i);
            }
            channel.flush();
            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ProtoBufSendClient().runClient();
    }
}
